﻿package com.cilico.single.view;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import com.cilico.single.ConfigManager;
import com.cilico.single.R;
import com.cilico.single.components.Alert;
import com.cilico.single.components.Component;
import com.cilico.single.components.ImageItem;
import com.cilico.single.components.Label;
import com.cilico.single.components.POI;
import com.cilico.single.components.Paging;
import com.cilico.single.components.Select;
import com.cilico.single.components.TabBar.ContentLayout;
import com.cilico.single.components.mButton;
import com.cilico.single.utils.Utils;

public class LoginView extends BaseView {
	static final int CHANNEL_LIST = 0;
	static final int POI_LIST = 1;
	static final int POI_ONLY_ONE = 2;

	// type of current tab bar, the value is one of COLLECTION, CHANNEL
	boolean isAddChannelHistory_;
	boolean isShowEntry_;
	boolean isShowQueryView_;
	// special items for poi detail.
	POI currentDisplayPoi_; // save current display poi, we need to keep track.
	// type of current detail, the value is one of CHANNEL_LIST, POI_LIST,
	// POI_DETAIL
	int detailType_;
	private Label name_;
	private Label phone_;
	private Label url_;
	Label showEntries_;
	protected Vector<ImageItem> images_;
	private Vector<Label> extAttrs_; // List of extended attributes as LPListItems
	LoginController loginController_;

	static ArrayList<ContentLayout> MANAGERLIST_;
	public boolean isExit = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activities_.add(this);    //把当前Activity放入集合中
		MANAGERLIST_ = new ArrayList<ContentLayout>();
		name_ = new Label(this, "", false, true, true);
		name_.textColor_ = Utils.WHITE;
		ConfigManager.currentView_ = this;
		initScreenManager(this);
		addTitleBar();
		// 设置背景图片
		setBackgroundResource(R.drawable.background, this, 1);
		// 设置登录界面的按键响应监听
		loginController_ = new LoginController(this);
		setComponentLister(loginController_);
		if (null != mid_ && null != mid_.poiRepo_)
			populate((POI) mid_.poiRepo_.peekActionPoi());
		Utils.addManagerAndSetTop(this);
		MANAGERLIST_.add(this.tabBar_.llV_);
		titleBar_.object = this;
		if (BaseView.mid_.poiRepo_.actionV_!=null&&BaseView.mid_.poiRepo_.actionV_.size()==1) {
			titleBar_.showBack_ = false;
		}
	}

	/**
	 * 当屏幕横竖切换时调用此方法
	 * */
	public void onConfigurationChanged(Configuration newConfig) {
		llUp_.removeAllViews();
		int roientation = this.getResources().getConfiguration().orientation;
		// 横竖屏切换时调用此方法交换宽高
		changeScreenWidthHeight(roientation);
		// delete titleBar!!!
		// titleBar_.setWidth(Utils.screenWidth_);
		// llUp_.addView(titleBar_);
		// 这里必须调用父类的onConfigurationChanged方法，否则报异常
		super.onConfigurationChanged(newConfig);
	}

	public void populate(POI poi) {
		resetDetailType();
		setShowDetail(poi);
	}

	void resetDetailType() {
		/* set the below(detail) type */
		Channel ch = BaseView.mid_.topChannelRepo_.getCurrentChannel();
		// We should check if the current channel is a colletion or not.
		if (ch != null && ch.isCollection_) {
			detailType_ = CHANNEL_LIST;
		} else {
			detailType_ = POI_LIST;
		}
	}

	void setShowDetail(POI poi) {
		removeCountLabel();
		removeAll();
		
		try {
			
			setPOIDetailContents(null, poi);
			final int size = mid_.poiRepo_.getActionSize();
			// 在注册界面没有标题栏
			if (size > 1 && !Utils.hiddenTitleBar_) {
				// 该判断表示当前界面并不是注册界面的最初级界面，应该在titlebar上加上返回按钮图标
				this.setLeftMenuMode(BaseView.BACK_MENU);
				if (null != leftMenuText_ && null != titleBar_) {
					this.titleBar_.showBack_ = true;
					this.titleBar_.backText_ = leftMenuText_;
					if (size > 2){
						this.titleBar_.showHeader_ = true;
					}
				}
			} else if (!Utils.hiddenTitleBar_){
				// 该判断表示当前界面是注册界面的最初级界面，不应该在titlebar上加上返回按钮图标
				this.setLeftMenuMode(BaseView.NO_MENU);
				if (null == leftMenuText_ && null != titleBar_) {
					this.titleBar_.showBack_ = false;
					this.titleBar_.backText_ = null;
				}
			}
			
		} catch (Exception e) {
			Utils.printException(e);
		}
	}

	private static StringBuffer getPhoneNumber(String text, String init) {
		char[] str = text.toCharArray();
		StringBuffer number = new StringBuffer(init);
		for (int i = 0; i < str.length; ++i) {
			if (str[i] >= '0' && str[i] <= '9')
				number.append(str[i]);
		}
		return number;
	}

	private void setPOIDetailContents(DisplayPoi disPoi, POI referPoi) throws Exception {
		POI poi = referPoi;
		if (referPoi == null && disPoi != null) {
			poi = disPoi.poi_;
		}
		currentDisplayPoi_ = poi;
		if (poi == null)
			return;
		// address links to phone
		// if (poi.adString_ != null && poi.adUrl_ != null) {
		// adMobile_.setText(poi.adString_);
		// append(adMobile_);
		// }
		// append poi name on the top.
		StringBuffer name = new StringBuffer();
		if (disPoi != null && (detailType_ != POI_ONLY_ONE)) {
			name.append(disPoi.getDisplayIndex());
			name.append(". ");
		}
		if (poi.name() != null)
			name.append(poi.name());
		// if (name.length() > 0 && (detailType_ != POI_ONLY_ONE)) {
		// name_.setText(name.toString());
		// name_.focus_ = false;
		// append(name_);
		// appendAtFixP(name_);
		// }

		if (poi.totalImages_ > 0) {
			poi.CalculateImgSize();
			images_ = new Vector<ImageItem>();
			for (int i = 0; i < poi.totalImages_; i++) {
				ImageItem image = new ImageItem(this);
				if (poi.imgUrls_.elementAt(i) != null && i >= poi.images_.size()) {
					// 该处为图片为下载完成时添加正在载入效果图片
					image.setImage(Utils.createImgWaitLoad(mid_, null, 0x88888888, 0, 0));
				} else {
					image.setImage((Bitmap) poi.images_.elementAt(i));
				}
				String link = null;
				link = (String) poi.imgLinks_.elementAt(i);
				if (link == null) {
					link = (String) poi.imgUrls_.elementAt(i);
				}
				image.setUrl(link);
				images_.insertElementAt(image, i);
				// Get the index of the first image in this view, we will use it
				// when we would link these images in the browser.
			}
		}

		if (poi.phone_ != null) {
			StringBuffer number = getPhoneNumber(poi.phone_, "");
			if (number.length() >= 7) {
				phone_.setText(poi.phone_);
				phone_.focus_ = false;
				append(phone_);
				appendAtFixP(phone_);
			}
		}
		int numExtAttr = poi.eattrNames_.size();
		if (numExtAttr > 0) {
			int oldSize = extAttrs_.size();
			int i;
			Label item = null;
			for (i = 0; i < oldSize; ++i) {
				item = (Label) extAttrs_.elementAt(i);
				if (i % 2 == 0) {
					item.setText((String) poi.eattrNames_.elementAt(i));
				} else {
					item.setText((String) poi.eattrValues_.elementAt(i));
				}
				item.setWidth(Component.MAX_WIDTH);
				append(item);
				appendAtFixP(item);
			}
			for (i = oldSize; i < numExtAttr; ++i) {
				if ((i - oldSize) % 2 == 0) {
					item = new Label(this, (String) poi.eattrNames_.elementAt(i), false, false, false);
				} else {
					item = new Label(this, (String) poi.eattrValues_.elementAt(i), false, false, false);
				}
				item.setWidth(Component.MAX_WIDTH);
				append(item);
				appendAtFixP(item);
				extAttrs_.addElement(item);
			}
		}
		Utils.parseUsingkXML(poi.desc_, this);

		// Link to the URL of the detail of this POI.
		if (poi.url_ != null && poi.url_.length() > 0) {
			url_.focus_ = false;
			append(url_);
			appendAtFixP(url_);
		}

		if (poi.showEntryUrl_ != null && poi.showEntryLen_ > 0) {
			showEntries_.focus_ = false;
			append(showEntries_);
			appendAtFixP(showEntries_);
		}
	}

	void countDownTime() {
		StringBuffer sb = new StringBuffer(countLabel_.getText());
		sb.deleteCharAt(Integer.parseInt(countLabel_.offset_));
		countLabel_.setText(sb.toString());
		if (countLabel_.delaytime_ == 0) {
			countLabel_.offset_ = null;
			countLabel_.setText(countLabel_.caption_);
			countTimer_.cancel();
		}
		if (countLabel_.delaytime_ > 0)
			countLabel_.delaytime_--;
	}


	/**
	 * When we go back we should re-set current item to be the current channel.
	 */
	public void keyBackPressed() {
		if (istimeout_){
			Alert.exitSystem(this);
			return;
		} 
		if (Select.ISRUNNING)
			Select.ISRUNNING = false;
		if (null != titleBar_ && !isExit) {
			// 该判断表示当前界面并不是注册界面的最初级界面，应该在titlebar上加上返回按钮图标
			final int size = mid_.poiRepo_.getActionSize();
			if (size <= 1) {
				tabBar_.replaceContentView((ContentLayout) LoginView.MANAGERLIST_.get(0));
				refresh();
				setLeftMenuMode(BaseView.NO_MENU);
				if (null == leftMenuText_) {
					titleBar_.showBack_ = false;
				}
			} else {
				View view = popContentStack();

				if (view != null) {
					// 如有不需要弹栈的时候则采用该方法换界面
					resetMiddlePanel(view, false);
					if (isContentStackEmpty()) {
						isInCeAirCjrLxrDiv_ = false;
					}
				} else {
					// 先删除当前的poi
//					mid_.poiRepo_.popActionPoi();
//					final POI ptemp = (POI) mid_.poiRepo_.peekActionPoi();
					
					Object o = mid_.poiRepo_.peekActionPoi();
					boolean firstPOINotSkip = true;
					while (true) {
						if ((o instanceof POI) && ((POI) o).skip_) {
							// 如果o是POI，且此POI的skip_为真，则继续弹栈
							mid_.poiRepo_.popActionPoi();
							o = mid_.poiRepo_.peekActionPoi();
							firstPOINotSkip = false;
						} else {
							if (firstPOINotSkip) {
								mid_.poiRepo_.popActionPoi();
								o = mid_.poiRepo_.peekActionPoi();
							}
							break;
						}
					}
					final POI p = (POI) o;
					mid_.waitDialog_.setDisplayTaskStatus(false);
					// 先显示进度条，然后延迟XX时间执行联网更新操作，否则进度条无法显示出来
					mid_.waitDialog_.showProgressdialog(this);
					new Timer().schedule(new TimerTask() {

						public void run() {
							if (size == 2 || size == 3) {
//								deleteTitleBar();
							}
							setShowDetail(p);
							Utils.addManagerAndSetTop(LoginView.this);
						}

					}, 600);
				}
			}
		} else {
			// 该判断表示当前界面是注册界面的最初级界面，不应该在titlebar上加上返回按钮图标
			Alert.exitSystem(this);
		}

	}

	void keyActionSoftKey() {
		View view;
		// 获取中间layout的控件总数
		int sizeMid = this.tabBar_.getContentChildCount();
		// 遍历控件
		for (int i = 0; i < sizeMid; i++) {
			view = this.tabBar_.getContentChild(i);
			if (view instanceof FormLayout) {
				FormLayout fl = (FormLayout) view;
				int sizeForm = fl.getChildCount();
				for (int n = 0; n < sizeForm; n++) {
					view = fl.getChildAt(n);
					// 是否为Button
					if (view instanceof mButton) {
						mButton button = (mButton) view;
						String name = button.attrName_;
						if (null == name) {
							// 用户点击了“提交”按钮
							FormAction faction = getFormByComponent(view);
							if (faction != null)
								faction.PostForm((mButton) view, this);
						} else if (name.equalsIgnoreCase("ewp_login_app")) {
							// 用户点击了“登录”按钮
							FormAction faction = getFormByComponent(view);
							if (faction != null)
								faction.PostForm((mButton) view, this);
						}
					}
				}
			}
		}
	}


	private void pressBackMenu() {
		// 菜单命令为退出时操作
		if (partScreenWait_ == null) {
			keyBackPressed();
		} else {
			// partScreenWait_.keyGameAction();待议
		}
	}

	// 按键操作
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if (!titleBar_.showBack_) {
				isExit = true;
			}
			if (titleBar_.showBack_) {
				titleBar_.showBack_ = false;
				isExit = false;
			}
			pressBackMenu();
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	Paging getPoiListPaging() {
		return mid_.getCurrentPoiSelection(false, this).getPaging();
	}

	/** over write */
	@Override
	public void dealWithLink(String link, BaseView bv, Boolean bl) {
		if (link != null) {
			link = link.trim();
			if (link.startsWith("lp:")) {
				String url = "http" + link.substring(2);
				String body = null;
				int index = url.indexOf("?");
				if (index != -1) {
					body = url.substring(index + 1);
					url = url.substring(0, index);
				}
				// add _s for the controllers.
//				Channel ch = mid_.topChannelRepo_.getCurrentChannel();
				// if (null != ch && ch.isSecure_) {
				String temphost = null;
				int indexC = url.indexOf("/channel/");
				int indexA = url.indexOf("/atompub/");
				int indexG = url.indexOf("/gdb/");
				if (indexC != -1) {
					temphost = url.substring(0, indexC) + "/channel_s/" + url.substring(indexC + "/channel/".length());
				} else if (indexA != -1) {
					temphost = url.substring(0, indexA) + "/atompub_s/" + url.substring(indexA + "/atompub/".length());
				} else if (indexG != -1 && url.indexOf("reg_notice") == -1 && url.indexOf("reg_wyxieyi") == -1){ //|| url.indexOf("reg_wyxieyi") == -1
					temphost = url.substring(0, indexG) + "/gdb_s/" + url.substring(indexG + "/gdb/".length());
				}
				if (temphost != null)
					url = temphost;
				Utils.printOutToConsole("+++ dealWithLink() +++ body:\n" + body);
				mid_.channelEntity_.loadLinkContentLogin(url, body, bv);
			} else if (link.startsWith("channel:")) {
				// URL syntax: channel://host/atompub/chlink/channel_id? or URL
				// syntax: channel://host/atompub/chlink/channel_id/...?
				final String chform = "chlink/";
				int id1 = link.indexOf(chform);
				int id2 = -1;
				int tmp = link.indexOf('/', id1);
				int tmp1 = link.lastIndexOf('/');
				if (tmp == tmp1) {
					id2 = link.indexOf("?", id1 + chform.length());
				} else {
					id2 = tmp1;
				}
				String channelId = null;
				channelId = link.substring(id1 + chform.length(), id2);

				String url = "http" + link.substring(7);
				String body = null;
				int index = url.indexOf("?");
				if (index != -1) {
					body = url.substring(index + 1);
					url = url.substring(0, index);
				}
				String temphost = null;
				int indexC = url.indexOf("/channel/");
				int indexA = url.indexOf("/atompub/");
				if (indexC != -1) {
					temphost = url.substring(0, indexC) + "/channel_s/" + url.substring(indexC + "/channel/".length());
				} else if (indexA != -1) {
					temphost = url.substring(0, indexA) + "/atompub_s/" + url.substring(indexA + "/atompub/".length());
				}
				if (temphost != null)
					url = temphost;
				Utils.printOutToConsole("body ==== " + body);
				mid_.channelEntity_.switchChannel(bv, channelId, false, url, body, false);
			} else if (link.startsWith("showBranch:/")) {
				POI p = currentDisplayPoi_;
				mid_.poiRepo_.entryUrl_ = ConfigManager.SERVER_URI + link.substring(12);
				mid_.channelEntity_.loadContentEntry(p, bv);
			} else {
				super.dealWithLink(link, bv, false);
			}
		}
	}
	
	public void onDestory() {
		activities_.remove(this); // 把当前Activity从集合中移除
	}
}
